import React from 'react'
import $ from 'jquery'
import dispatcher from 'lib/dispatcher'
import Modal from 'lib/components/Modal.jsx'
import {saveDashboardApi,updateDashboardApi} from '../apis/validApis/dashboard'
import {Success,Info,Warning} from 'lib/components/Notify.jsx'
export default class SettingView extends Modal {
  constructor(props){
    super(props)
    this.state = {
      msg:''
    }
    this.createAction = this.createAction.bind(this)
    this.renameAction = this.renameAction.bind(this)
  }
  createAction(){
    var _this = this
    if(this.state.saving){
      return ;
    }
    saveDashboardApi({
      name:$(this.refs.dashboardName).val()
    }).post().then(function(res,params){
      if(res.id){
        dispatcher.dispatch({
          $type:'create_dashboard',
          name:params.name
        })
        _this.close();
      }else{
        _this.setState({
          saving:false,
          msg:'保存失败'
        })
      }
    },function(err){
      _this.setState({
        saving:false,
        msg:err.msg||err.message //'保存失败'
      })
    },function(){
      _this.setState({
        saving:true,
        msg:null
      })
    })
  }
  renameAction(){
    var _this = this
    if(this.state.saving){
      return ;
    }
    updateDashboardApi({
      id:this.props.dashboardId,
      name:$(this.refs.dashboardName).val()
    }).post().then(function(res,params){
      if(res.result){
        Success('修改成功！')
        dispatcher.dispatch({
          $type:'rename_dashboard',
          id:params.id,
          name:params.name
        })
        _this.close();
      }else{
        _this.setState({
          saving:false,
          msg:'保存失败'
        })
      }
    },function(err){
      _this.setState({
        saving:false,
        msg:err.msg||err.message //'保存失败'
      })
    },function(){
      _this.setState({
        saving:true,
        msg:null
      })
    })
  }
  renderHeader(){
    return (
      <h4>仪表盘信息</h4>
    )
  }
  renderBody(){
    return (
      <div className="form-group horizontal">
        <ul>
          <li>
            <label htmlFor="account-name" className="control-label">仪表盘名称</label>
            <input className="input-text" ref="dashboardName" defaultValue={this.props.dashboardName} />
            <span className="msg-error">{this.state.msg}</span>
          </li>
        </ul>
      </div>
    )
  }
  renderFooter(){
    return (
      <div>
        {
          this.state.saving?(
            <span>保存中...</span>
          ):(
            <button className="btn-green"
              onClick={this.props.dashboardId?this.renameAction:this.createAction}
              type="button">
              保存
            </button>
          )
        }
      </div>
    )
  }
}
